
const cloud = require('tcb-admin-node');
const tcbConfig = { env: 'meatom04-01-2gue0fnr49a26808' }; //当前环境 ENV_ID
const auth = cloud.init(tcbConfig).auth();
const db = cloud.database();

let upload_uid
let platform
// 时间戳转换时间格式
Date.prototype.Format = function (fmt) {
  var o = {
    "M+": this.getMonth() + 1, // 月份
    "d+": this.getDate(), // 日
    "h+": this.getHours(), // 小时
    "m+": this.getMinutes(), // 分
    "s+": this.getSeconds(), // 秒
    "q+": Math.floor((this.getMonth() + 3) / 3), // 季度
    "S": this.getMilliseconds() // 毫秒
  };
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(RegExp.$1, (this.getFullYear() + ""));
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
}
// 检查openid是否有用户
function checkOpenid(res) {
  if (res.data && res.data.length) {
    let userInfo = res.data[0]
    return dealUserInfo(userInfo)
  } else {
    return checkUid()
  }
}
// 检查uid是否有用户
function checkUid() {
  return db.collection('User').where({
    uid: upload_uid
  }).limit(1).get().then(returnUidUser).catch(initUser)
}
// 返回uid 用户
function returnUidUser(res) {
  if (res.data && res.data.length) {
    let userInfo = res.data[0]
    return dealUserInfo(userInfo)
  } else {
    return initUser()
  }
}
// 用户信息处理，一般是跨天等时间处理
function dealUserInfo(userInfo) {
  userInfo.last_time = (new Date()).valueOf() // 最后登录时间覆盖
  // 更新储存
  return db.collection('User').where({
    uid: userInfo.uid
  }).update({
    // data: {
    last_time: userInfo.last_time
    // },
  })
    .then(res => {
      return to_json(userInfo)
    })
    .catch(fail => {
      return to_json(userInfo)
    })
}

// fin 最后一步 数据格式转换
function to_json(userInfo) {
  userInfo.last_time_stamp = userInfo.last_time
  userInfo.last_time = new Date(userInfo.last_time).Format('yy-MM-dd hh:mm:ss')
  return userInfo
}

// 初始化用户信息
function initUser() {
  let userInfo = {}
  // const wxContext = cloud.getWXContext()
  // userInfo.openid = wxContext.OPENID

  userInfo.old = true
  userInfo.coin = 2000
  userInfo.diamond = 0
  userInfo.bagNum = 20
  userInfo.bag = [
    { id: 11001, num: 50 },
    { id: 11006, num: 50 },
    { id: 11007, num: 50 },
    { id: 20002, num: 250 },
  ]
  userInfo.last_time = (new Date()).valueOf()
  userInfo.team = [
    {
      id: 1001,               // 角色编号
      order: 1,              // 站位排序
      equips: [1, 0, 0, 0],     // 装备等级
      hand: 0                 // 选择装备
    }
  ]
  userInfo.pass_list = [
  ]
  // 角色技能卡片背包
  userInfo.card = [
    { id: 3001, lv: 1 },
  ]
  // 卡片队伍
  userInfo.card_team = [
  ]
  userInfo.platform = platform
  // 入库，成功则返回存档，失败则重新登录
  return db.collection('User').orderBy('uid', 'desc').limit(1).get().then(
    res => {
      let uid = 1
      if (res && res.data && res.data.length) {
        uid = res.data[0].uid + 1
      }
      userInfo.uid = uid
      return db.collection('User').add(userInfo).then(add_res => {
        return to_json(userInfo)
      }).catch(fail => {
        return null
      })
    }
  ).catch(fail => {
    return null
  })
}

exports.main = async (event, context) => {
  upload_uid = event.uid
  platform = event.platform
  // 此处为微信登录
  // const wxContext = cloud.getWXContext()
  // console.log(wxContext.OPENID, 'openid')
  // let returnUser = db.collection('User').where({
  //   openid: wxContext.OPENID
  // }).limit(1).get().then(checkOpenid).catch(checkUid)
  // let returnUser = checkUid()
  // return await returnUser
  // callback(null, checkUid);
  return await checkUid()
}

